package com.heba.greenmulu;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.heba.ATApp;
import com.heba.AppManager;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.config.CommonConfig;
import com.heba.dialog.ErrorDialog;
import com.heba.event.MessageEvent;
import com.heba.fragment.GuideFragment;
import com.heba.fragment.business.BusinessFragment;
import com.heba.fragment.diary.DiaryFragment;
import com.heba.fragment.home.HomeFragment;
import com.heba.fragment.message.MessageFragment;
import com.heba.fragment.message.MessageNewFragment;
import com.heba.fragment.mine.MineNewFragment;
import com.heba.fragment.product.ShopListFragment;
import com.heba.fragment.scan.ScanFragment;
import com.heba.greenmulu.diary.ItemPersonHomePageActivity;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.greenmulu.user.UserDiaryListActivity;
import com.heba.helper.MemberShipHelper;
import com.heba.permission.PermissionHelper;
import com.heba.utils.GlideUtil;
import com.heba.utils.ImageTools;
import com.heba.utils.StatusBarUtils;
import com.leaf.library.StatusBarUtil;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * 主页面框架
 * <p>
 * Created by jason on 2019/2/12.
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {
    // 默认是日间模式
    private int theme = R.style.AppTheme;
    private LinearLayout linear_home;   //home页面
    private LinearLayout linear_scan;   //扫描产品页面
    private LinearLayout linear_diary;  //日记页面
    private LinearLayout linear_message;  //通讯录页面
    private LinearLayout linear_mine;    //我的页面
    private ImageView iv_mine;
    private ConstraintLayout alert_view;
    /**
     * FragmentManager管理
     */
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private List<Fragment> fragments;

    private HomeFragment homeFragment;
    private ScanFragment scanFragment;
    private DiaryFragment diaryFragment;
    private MessageNewFragment messageFragment;
    private MineNewFragment mineFragment;
    private BusinessFragment businessFragment;
    private ShopListFragment shopListFragment;

    int currentPosition = 0;   //选中页面

    private Bitmap bitmap;   //去除色彩的Bitmap头像
    private static final int LOCATION_CODE = 1;
    /**
     * 位置权限
     */
    public void getLocationPermission(final Activity context) {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(context,
                            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
                }
            }
        } catch (SecurityException e) {
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册EventButs
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        findViewById();
        initView();
        getUpdateVer();
//        preloadBitmapIcon(Cfg.Icon);
        initFragment();
        getCameraPermission();
        getLocationPermission(this);
        /**
         * 极光推送保存设备到服务器
         */
        String registrationID = JPushInterface.getRegistrationID(this);
        Debug.Log("JPUSH registrationID is ", registrationID);
        saveDevice2Server(registrationID);
//        StatusBarUtils.setStatusLightMode(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 只要发生onSaveInstanceState就remove all Fragment
        if (outState != null) {
            outState.remove("android:support:fragments");
        }
    }

    @Override
    protected void findViewById() {
        alert_view = findViewById(R.id.alert_view);
        linear_home = findViewById(R.id.linear_home);
        linear_scan = findViewById(R.id.linear_scan);
        linear_mine = findViewById(R.id.linear_mine);
        linear_diary = findViewById(R.id.linear_diary);
        linear_message = findViewById(R.id.linear_message);
        iv_mine = findViewById(R.id.iv_mine);
    }

    @Override
    protected void initView() {
        linear_home.setOnClickListener(this);
        linear_scan.setOnClickListener(this);
        linear_mine.setOnClickListener(this);
        linear_diary.setOnClickListener(this);
        linear_message.setOnClickListener(this);
    }

    /**
     * 预加载头像,获取bitmap对象
     */
    private void preloadBitmapIcon(String url) {
        Glide.with(this).asBitmap().load(url).listener(new RequestListener<Bitmap>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                bitmap = ImageTools.toGrayScale(resource);
                iv_mine.setImageBitmap(bitmap);
                return false;
            }
        }).preload();
    }

    /**
     * initFragment
     */
    private void initFragment() {
        homeFragment = new HomeFragment();
        shopListFragment = new ShopListFragment();
        diaryFragment = new DiaryFragment();
        messageFragment = new MessageNewFragment();
        mineFragment = new MineNewFragment();
        businessFragment = new BusinessFragment();
        fragments = new ArrayList<>();
        fragments.add(homeFragment);

        if (Cfg.SessionKey.isEmpty()){
            GuideFragment guideFragment1 = new GuideFragment();
            fragments.add(guideFragment1);
            GuideFragment guideFragment2 = new GuideFragment();
            fragments.add(guideFragment2);
            GuideFragment guideFragment3 = new GuideFragment();
            fragments.add(guideFragment3);
            GuideFragment guideFragment4 = new GuideFragment();
            fragments.add(guideFragment4);
        }else{
            fragments.add(shopListFragment);
            fragments.add(diaryFragment);
            fragments.add(messageFragment);
            if (Cfg.AccountType.equals("0")) {
                fragments.add(mineFragment);
            }else{
                fragments.add(businessFragment);
            }
        }


        //默认显示第一个fragment
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.linear_fragment, fragments.get(0));
        fragmentTransaction.commit();

        linear_home.setSelected(true);

    }

    @Override
    public void onClick(View v) {
        setFragmentSelected(v);
        switch (v.getId()) {
            case R.id.linear_home:
                getFragment(0);
                EventBus.getDefault().post(new MessageEvent(CommonConfig.HOME_REFRESH));
                break;
            case R.id.linear_scan:
                getFragment(1);
                EventBus.getDefault().post(new MessageEvent(CommonConfig.UPDATE_SHOP_LIST));
                break;
            case R.id.linear_diary:
                getFragment(2);
                if (!Cfg.SessionKey.isEmpty()) {
                    EventBus.getDefault().post(new MessageEvent(CommonConfig.EVENT_MAIN_CLICK_REFRESH_DIARY_LIST));
                }
                break;
            case R.id.linear_message:
                getFragment(3);
                if (!Cfg.SessionKey.isEmpty()) {
                    EventBus.getDefault().post(new MessageEvent(CommonConfig.NOTIFICATION_REFRESH));
                }
                break;
            case R.id.linear_mine:
                getFragment(4);
                if (!Cfg.SessionKey.isEmpty()) {
//                    GlideUtil.loadImageWithPlaceHolderID(this, Cfg.Icon, iv_mine, R.drawable.icon_head_portrait);
                    EventBus.getDefault().post(new MessageEvent(CommonConfig.DIARY_REFRESH));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 设置选中的fragment
     *
     * @param view
     */
    private void setFragmentSelected(View view) {
        linear_home.setSelected(false);
        linear_scan.setSelected(false);
        linear_diary.setSelected(false);
        linear_message.setSelected(false);
        linear_mine.setSelected(false);
        view.setSelected(true);
        if (null != bitmap)
            iv_mine.setImageBitmap(bitmap);
    }

    /**
     * Fragment的切換
     *
     * @param position
     */
    public void getFragment(int position) {
        Fragment fragment = fragments.get(position);
        FragmentTransaction ft = obtainFragmentTransaction(position);
//        getCurrentFragment().onPause();
        if (fragment.isAdded()) {
//            fragment.onResume();
        } else {
            ft.add(R.id.linear_fragment, fragment);
        }
        showFragment(position);
        ft.commit();
    }

    /**
     * showFragment
     *
     * @param idx
     */
    public void showFragment(int idx) {
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            FragmentTransaction ft = obtainFragmentTransaction(idx);
            if (idx == i) {
                ft.show(fragment);
            } else {
                ft.hide(fragment);
            }
            ft.commit();
        }
        currentPosition = idx;
    }

    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        return ft;
    }

    public Fragment getCurrentFragment() {
        return fragments.get(currentPosition);
    }

    /**
     * 获取摄像头权限
     */
    private void getCameraPermission() {
        new PermissionHelper(this, new PermissionHelper.PermissionListener() {
            @Override
            public void onPermissionSuccess() {
            }

            @Override
            public void onPermissionFailure() {

            }
        }).requestPermission(Permission.CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Debug.Log(this.getClass().getSimpleName(), "onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        Fragment f = fragmentManager.findFragmentById(R.id.linear_fragment);
        f.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MemberShipHelper.isLogin()) {
            getBrowserData();
        } else {
//            MemberShipHelper.logOut();
//            openActivity(GuideActivity.class);
//            AppManager.getAppManager().finishAllActivity();
        }
        StatusBarUtils.setStatusLightMode(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * 判断是否有浏览器传递参数进来
     */
    private void getBrowserData() {
        Intent intent = getIntent();
        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            Uri uri = intent.getData();
            if (uri != null) {
                //取出数据
                String action = uri.getQueryParameter("action");
                String value = uri.getQueryParameter("value");

                Bundle bundle = new Bundle();
                switch (action) {
                    case "ProductDetail":
                        if (!value.isEmpty()) {
                            int length = Integer.valueOf(value.substring(1, 2));
                            String productID = value.substring(2, 2 + length);
                            bundle.putString(CommonConfig.PRODUCT_ID, productID);
                            openActivity(ItemProductDetailActivity.class, bundle);
                            intent.setData(null);
                        }
                        break;
                    case "User":
                        if (!value.isEmpty()) {
                            int length = Integer.valueOf(value.substring(1, 2));
                            String userID = value.substring(2, 2 + length);
                            bundle.putString(CommonConfig.SEND_USER_ID, userID);
                            openActivity(ItemPersonHomePageActivity.class, bundle);
                            intent.setData(null);
                        }
                        break;
                    case "Diary":
                        if (!value.isEmpty()) {
                            int length = Integer.valueOf(value.substring(1, 2));
                            String diaryID = value.substring(2, 2 + length);
                            bundle.putInt(CommonConfig.TYPE, 1);
                            bundle.putString(CommonConfig.DIARY_ID, diaryID);
                            openActivity(UserDiaryListActivity.class, bundle);
                            intent.setData(null);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 存储设备信息到服务器
     *
     * @param registrationID
     */
    public void saveDevice2Server(String registrationID) {
        StringBuffer timeLimit = new StringBuffer();
        if (!Cfg.isPushTime1) {
            timeLimit.append(1);
            timeLimit.append(",");
        }
        if (!Cfg.isPushTime2) {
            timeLimit.append(2);
            timeLimit.append(",");
        }
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {

            }

            @Override
            public void Fail(String error) {

            }
        }).saveDevice(this, Cfg.UserID, registrationID, timeLimit.toString().isEmpty() ? "" : timeLimit.deleteCharAt(timeLimit.length() - 1).toString());
    }

    /**
     * 获取最新版本号
     */
    private void getUpdateVer() {
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                if (Float.parseFloat(Cfg.appVersionName) < Cfg.AppVer) {
                    //不是最新版本，显示对话框前往googleplay更新
                    ErrorDialog.showWithConfirmClick(mContext, "", getResources().getString(R.string.public_update_content), getResources().getString(R.string.public_update_now),
                            (dialog, which) -> {
                                ATApp.getApplication().launchAppDetail(BuildConfig.APPLICATION_ID, "com.android.vending");
                            });
                }
            }

            @Override
            public void Fail(String error) {

            }
        }).checkAppUpdate(MainActivity.this);
    }

    /**
     * 判断退出APP
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), this.getString(R.string.out_app), Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 接收EventBus
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 修改头像时更新
         */
        if (event.getEvent().equals(CommonConfig.EVENT_UPDATE_ICON)) {
            preloadBitmapIcon(event.getUserIcon());
        }
        if (event.getEvent().equals(CommonConfig.NOTIFY_ALERT)){
            alert_view.setVisibility(View.VISIBLE);
            TextView textView = alert_view.findViewById(R.id.content);
            String accountType = event.getAccountType();
            String statueType = event.getStatueType();
            textView.setText((statueType.equals("1"))?R.string.pass_business:R.string.fail_business);
            Cfg.change("AccountType",accountType);
            Button clickBtn = alert_view.findViewById(R.id.btn_comment_add);
            clickBtn.setOnClickListener(v->{
                AppManager.getAppManager().finishAllActivity();
                openActivity(MainActivity.class);
                if (Cfg.AccountType.equals("1")){
                    Toast.makeText(getApplicationContext(),this.getString(R.string.change_alert_brand), Toast.LENGTH_SHORT).show();
                }else if (Cfg.AccountType.equals("2")){
                    Toast.makeText(getApplicationContext(),this.getString(R.string.change_alert_org), Toast.LENGTH_SHORT).show();
                }else if(Cfg.AccountType.equals("3")){
                    Toast.makeText(getApplicationContext(),this.getString(R.string.change_alert_cer), Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getApplicationContext(), this.getString(R.string.change_alert_normal), Toast.LENGTH_SHORT).show();
                }


            });

        }
        if(event.getEvent().equals(CommonConfig.NOTIFY_CHANGE_TYPE)){
            if (Cfg.AccountType.equals("1")){
                Toast.makeText(getApplicationContext(), this.getString(R.string.change_alert_brand), Toast.LENGTH_SHORT).show();
            }else if (Cfg.AccountType.equals("2")){
                Toast.makeText(getApplicationContext(), this.getString(R.string.change_alert_org), Toast.LENGTH_SHORT).show();
            }else if(Cfg.AccountType.equals("3")){
                Toast.makeText(getApplicationContext(), this.getString(R.string.change_alert_cer), Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(), this.getString(R.string.change_alert_normal), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //反注册
        EventBus.getDefault().unregister(this);
    }
}
